package com.example.mysecurity.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@EnableWebSecurity
@Configuration
public class SecurityConfig {
    //滤器链的相关设置
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        http.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> {
            authorizationManagerRequestMatcherRegistry
                    .requestMatchers("/stu/select").hasAuthority("stu:select") //需要有指定的权限
                    .requestMatchers("/stu/insert").hasAuthority("stu:insert") //需要有指定的权限
                    .requestMatchers("/stu/update").hasRole("管理员") //需要有指定的权限
                    .requestMatchers("/stu/list").hasRole("管理员") //需要有指定的权限
//                    .requestMatchers("/stu/del").hasRole("管理员")      //需要有指定的权限
                    .anyRequest().authenticated();
                });
        //        Form表单提交请求的处理。（可以为传统form表单提交，ajax提交）
        http.formLogin(httpSecurityFormLoginConfigurer -> {
            httpSecurityFormLoginConfigurer.loginPage("/login").permitAll()
                    .loginProcessingUrl("/loginButton")   //对照登录页面内提交的url，转交给com.example.myspringsecurity.service.impl.UserServiceImpl.loadUserByUsername方法
                    .successHandler((request, response, authentication) -> {
                        response.sendRedirect("/home");
                    })       //跳转，地址栏地址改变
            ;
        });
        //权限不够处理器
//        http.exceptionHandling(httpSecurityExceptionHandlingConfigurer -> {
//            httpSecurityExceptionHandlingConfigurer.accessDeniedHandler((request, response, accessDeniedException) -> {
//                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
//                response.setHeader("Content-Type","application/json;charset=utf-8");
//                PrintWriter out = response.getWriter();
//                out.write("{\"status\":\"error\",\"msg\":\"权限不足，请联系管理员!\"}");
//                out.flush();
//            });
//        });
//        Spring Security不会创建HttpSession，也不会使用它来获取用户信息
//        http.sessionManagement(httpSecuritySessionManagementConfigurer -> {
//            httpSecuritySessionManagementConfigurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
//        });
        //登出
        http.logout(httpSecurityLogoutConfigurer -> {
           httpSecurityLogoutConfigurer.logoutUrl("/logout")  //进入登出进程，内部销毁session
                   .logoutSuccessUrl("/login");
        });
//        关闭csrf防护
        http.csrf(httpSecurityCsrfConfigurer -> {
            httpSecurityCsrfConfigurer.disable();
        });

        return http.build();
    }

    //密码比较，加密器
    @Bean
    public PasswordEncoder getPwdEncoder() {
        return new BCryptPasswordEncoder();
    }
}
